/**
 * Author by justwen, Email 2422142078@qq.com, Date on 2021/3/12.
 * PS: Not easy to write code, please indicate.
 */
package com.example.myapp.Activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.MyDialog;
import com.example.myapp.ADO.SQLDAO;
import com.example.myapp.ADO.UpdateAppManager;
import com.example.myapp.Fragment.ContactFragment;
import com.example.myapp.Fragment.HomeFragment;
import com.example.myapp.Fragment.RecordFragment;
import com.example.myapp.Fragment.UserFragment;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Msg;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.Password;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.example.myapp.Model.MyData;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.update.BmobUpdateAgent;

public class Main extends AppCompatActivity {
    private RadioGroup mTabRadioGroup;
    private   RadioButton today_tab;
    private   RadioButton record_tab;
    private   RadioButton contact_tab;
    private   RadioButton settings_tab;
    private String   phone;
    private String  pwd;
    private    TextView msgcount;
    private SparseArray<Fragment> mFragmentSparseArray;
    private MyData myData;
    private int page=R.id.today_tab;
    private ShapeLoadingDialog shapeLoadingDialog;
    private Timer  timer;
    private  RequestQueue requestQueue;
    private JsonObjectRequest jsonObjectRequest;
    private  RequestQueue requestQueue2;
    private JsonObjectRequest jsonObjectRequest2;

    private String url="http://pybchat.justwen233.cn/findChatMsgCount";//我的所有聊天条数
    private String url2="http://pybchat.justwen233.cn/findReceiptgCount";//我已经接收所有聊天条数
    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    queryALLMsgs();

                    break;
                case 2:
                    UpdateAppManager manager=new     UpdateAppManager(Main.this);
                    manager.  getAdmiVsionMsg();

                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
//        BmobUpdateAgent.silentUpdate(this);
        Bmob.resetDomain("http://pybsdk.justwen233.cn/8/");
        Bmob.initialize(this, "33854715fa739da69a015d5ab944d101");
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_main);
        msgcount=findViewById(R.id.msgcount);

        myData=(MyData)getApplication();
        judgePermission();
        requestQueue = Volley.newRequestQueue(Main.this);
        requestQueue2 = Volley.newRequestQueue(Main.this);
        Bundle receive=getIntent().getExtras();
        if(receive!=null){
            page=receive.getInt("page");//打开首页
        }

        SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        if (sp.getBoolean("save", false) == true) {
            phone=sp.getString("phone","");
            pwd=sp.getString("pwd","");
            login(phone,pwd);
        }else {
            initView();
        }

        handler.sendEmptyMessage(2);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        Toast.makeText(Main.this,"销毁",Toast.LENGTH_SHORT).show();
        if (timer!=null){
            timer.cancel();
        }
    }


    /** 获取记录总量变动*/
    private  void queryALLMsgs(){
      if(!BmobUser.isLogin()){
           return;
         }
        Map<String,String> map=new HashMap<String,String>();
        map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
        JSONObject params=new JSONObject(map);
         jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if(response==null){
                    return;
                }
                try {
                    int  num = response.getInt("result");
                    Log.w("vivi", "onResponse: "+ num);
                    Map<String,String> map2=new HashMap<String,String>();
                    map2.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
                    JSONObject params=new JSONObject(map2);
                     jsonObjectRequest2 = new JsonObjectRequest(Request.Method.POST, url2, params, new com.android.volley.Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                int  num2 = response.getInt("result");
                                Log.w("vivi", "onResponse: "+ num2);
                                if(num-num2>0) {
                                    int shownum=num-num2;
                                    msgcount.setText(""+shownum);
                                    msgcount.setVisibility(View.VISIBLE);

                                }else {
                                    msgcount.setVisibility(View.INVISIBLE);
                                }
                            }catch (Exception e ){
                                Log.w("vivi", "onResponse: "+ e.getMessage());
                            }

                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                            Log.d("vivi", "error: " + error.getMessage());

                        }
                    });
                    //添加队列
                    requestQueue2.add(jsonObjectRequest2);
                    requestQueue2.cancelAll(jsonObjectRequest2);

                }catch (Exception e ){
                    Log.w("vivi", "vivi错误: "+ e.getMessage());
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());

            }
        });
        //添加队列
        requestQueue.add(jsonObjectRequest);
        requestQueue.cancelAll(jsonObjectRequest);


    }





    private void login(String phone, final String password) {
       BmobUser.logOut();
        BmobUser.loginByAccount(phone, password, new LogInListener<User>() {
            @Override
           public void done(User user, BmobException e) {
                   if (e == null) {
                       Log.w("aaaa", "登录成功->ID:" + user.getObjectId() + "----用户名:" + user.getUsername());
                       BmobFile bmobFile = user.getIcon();
                       myData.setIconfileName(bmobFile.getFilename());
                       myData.setUserName(user.getUsername());
                       myData.setObjID(user.getObjectId());
                       myData.setSex(user.getSex());
                       myData.setBirth(user.getBirth());
                       myData.setBirthPlace(user.getBirthPlace());
                       myData.setEmail(user.getMyEamil());
                       myData.setShow(user.getShow());
                       myData.setIconUrl(user.getIcon().getUrl());
                       initView();
                       Log.w("aaaa", "登录结束");
                       // TODO 设置定时器
                       timer = new Timer();
                       timer.schedule(new TimerTask() {
                           @Override
                           public void run() {
                               Message message = new Message();
                               message.what = 1;
                               handler.sendMessage(message);

                           }
                       }, 1000, 2000);  // TODO 每隔一秒执行一下


                   } else {
                       initView();
                       Log.w("aaaa", "登录失败：" + e.getErrorCode() + "-" + e.getMessage() + "\n");

                   }

            }
        });
    }




    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(Main.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }








    private void initView() {
        mTabRadioGroup = findViewById(R.id.tabs_rg);
        today_tab=findViewById(R.id.today_tab);
        record_tab=findViewById(R.id.record_tab);
        contact_tab=findViewById(R.id.contact_tab);
        settings_tab=findViewById(R.id.settings_tab);
        MyData data=(MyData)getApplication();

//        定义碎片构造数组
        mFragmentSparseArray = new SparseArray<>();
//        绑定每个Fragment碎片并且传一个参数
        mFragmentSparseArray.append(R.id.today_tab, HomeFragment.newInstance("首页"));
        mFragmentSparseArray.append(R.id.record_tab, RecordFragment.newInstance("失物招领"));
        mFragmentSparseArray.append(R.id.contact_tab, ContactFragment.newInstance("朋友"));
        mFragmentSparseArray.append(R.id.settings_tab, UserFragment.newInstance("主页"));
        mTabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 具体的fragment切换逻辑可以根据应用调整，例如使用show()/hide()
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        mFragmentSparseArray.get(checkedId)).commit();// 绑定对应碎片
            }
        });


           getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,mFragmentSparseArray.get(R.id.today_tab)).commit();


        if (page==R.id.contact_tab){
            contact_tab.setChecked(true);
        }
        if (page==R.id.today_tab){

            today_tab.setChecked(true);
        }
        if (page==R.id.record_tab){
            record_tab.setChecked(true);
        }
        if (page==R.id.settings_tab){

            settings_tab.setChecked(true);
        }
//  点击中间那个按钮
        findViewById(R.id.sign_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if(!BmobUser.isLogin()){
                    Toast.makeText(Main.this, "请登录后再操作！", Toast.LENGTH_LONG).show();

                    return;
                }
                AlertDialog.Builder builder =new AlertDialog.Builder(Main.this );
                builder.setTitle("请选择发布类别");
                String[] items={"发布动态","失物招领"};
                builder.setNegativeButton("取消",null);
                builder.setItems(items,(dialog, which) -> {
                    switch (which) {
                        case 0://发布动态
                        {
                            startActivity(new Intent(Main.this, AddArticle.class));

                        }  break;
                        case 1://失误招领
                        {
                            startActivity(new Intent(Main.this, AddRecord.class));

                            break;
                        }
                    }
                } );
                builder.show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        //此处写退向后台的处理

        Log.w("aaaa","我点击返回键！");
        View view = getLayoutInflater().inflate(R.layout.exit_dialog_layout, null);
        MyDialog   mMyDialog = new MyDialog(Main.this, 0, 0, view, R.style.DialogTheme);
        TextView exitall=  view.findViewById(R.id.exitall);
        TextView exitback=  view.findViewById(R.id.exitback);
        mMyDialog.setCancelable(true);
        mMyDialog.show();
        exitall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.getInstance().exit();
                finish();
            }
        });//退出程序
        exitback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMyDialog.dismiss();
            }
        });//退出程序


    }//手机返回键



    protected void judgePermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝

            // sd卡权限
            String[] SdCardPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, SdCardPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCardPermission, 100);
            }



            String[] READ_EXTERNAL_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, READ_EXTERNAL_STORAGE, 500);
            }



        }else{
            //doSdCardResult();
        }
        //LocationClient.reStart();

        boolean haveInstallPermission;




    }

}
